package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService {
    private RoleMapper roleMapper ;

    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }

    @Override
    public void insert(Role role) {
        roleMapper.insert(role);
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);
        roleMapper.deleteRelation(id);
    }

    @Override
    public void update(Role role) {
        roleMapper.updateByPrimaryKey(role.getId());
    }

    @Override
    public Role selectById(Long id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        return role ;
    }

    @Override
    public List<Role> selectAll() {
        List<Role> roles = roleMapper.selectAll();
        return roles ;
    }

    @Override
    public PageInfo<Role> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Role> roles = roleMapper.queryAll(qo);
        return new PageInfo<>(roles);
    }

    @Override
    public void insertRelation(Role role, Long[] ids) {
        roleMapper.insert(role) ;
        if (ids != null && ids.length>0){
            for (Long id : ids) {
                roleMapper.insertRelation(role.getId(),id);
            }
        }
    }

    @Override
    public List<Role> selectRole(Long id) {
        List<Role> roles = roleMapper.selectRole(id);
        return roles ;
    }

    @Override
    public void updateRelation(Role role, Long[] ids) {
        roleMapper.updateRole(role);
        roleMapper.deleteRelation(role.getId());
        if (ids != null && ids.length>0){
            for (Long id : ids) {
                roleMapper.insertRelation(role.getId(),id);
            }
        }
    }

    @Override
    public List<Role> selectOwnRole(Long id) {
        List<Role> roles = roleMapper.selectOwnRole(id);
        return roles ;
    }
}
